//
// Created by richa on 2019/1/21.
//

#ifndef MODBUS_TCP_PLUGIN_H
#define MODBUS_TCP_PLUGIN_H

#include <thread>
#include <set>
#include "../modbus/modbus.h"

#if defined(_WIN32)
#include <ws2tcpip.h>
#else
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

class ModbusTcp {
private:
    const char * ip_addr;
    int listenPort = 10502;
    std::thread * listenThread;
    std::thread * replyThread;
    modbus_t * ctx;
    int max_connection = 5;
    int server_socket = -1;
    std::set<int> socketFdSet;
    int fdMax = 0;
    modbus_mapping_t * modbus_mapping;
    static void listenThreadFunc(ModbusTcp* p);
    static void replyThreadFunc(ModbusTcp* p);

public:
    ModbusTcp(const char *ip_addr, modbus_mapping_t *modbus_mapping);

public:
    virtual ~ModbusTcp();

    void startListen();
    void setListenPort(int port);
};


#endif //MODBUS_TCP_PLUGIN_H
